package com.spring.demo.dao.user.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.spring.demo.dao.user.UserDAO;
import com.spring.demo.model.user.User;

@Repository(UserDAO.DAO_NAME)
public class UserDAOImpl implements UserDAO {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Override
	public boolean saveOrUpdateUser(String sql,Object... params) {
		// TODO Auto-generated method stub
		int num = jdbcTemplate.update(sql, params);
		if(num>0){
			return true;
		}
		return false;
	}
	@Override
	public List<User> selectUser(String selectSql, Object... params) {
		// TODO Auto-generated method stub
		//这里如果实体类和数据库字段不完全匹配，不能再查询列表时直接指定实体类名，不能使用要不然会匹配不上，需要自己手动去匹配
		List<Map<String,Object>> list = jdbcTemplate.queryForList(selectSql, params);
		/*jdbcTemplate.query(sql, new ResultSetExtractor(
				public Object exObject));*/
		/*
		 * 也可以通过ResultSetExtractor、RowMapper、RowCallbackHandler这三个接口在查询过程中直接转换
		 * 详见  http://blog.csdn.net/chengly0129/article/details/50012801
		 */
		/*new ResultSetExtractor<List<User>>(){
			@Override
			public List<User> extractData(ResultSet rs) throws SQLException, DataAccessException {
				// TODO Auto-generated method stub
				return null;
			}
		};*/
		return objectToUser(list);
	}

	private List<User> objectToUser(List<Map<String,Object>> list){
		List<User> users = new ArrayList<>();
		if(list!=null&&list.size()>0){
			for (Map<String,Object> map : list) {
				User user = new User();
				user.setId((Long)map.get("id"));
				user.setUserName((String)map.get("user_name"));
				user.setPassWord((String)map.get("pass_word"));
				user.setIsOnline((Boolean)map.get("is_online"));
				user.setType((Integer)map.get("type"));
				user.setAge((Integer)map.get("age"));
				user.setDr((Integer)map.get("dr"));
				user.setLeader((Long) map.get("leader_id"));
				
				users.add(user);
			}
		}
		return users;
	}
}
